package com.itheima.controller.backend.security.security;

import com.itheima.Service.SetMealService;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("setmeal")
public class SetMealController {
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("add")
    public Result add(@RequestParam List<Integer>checkgroupIds,
                      @RequestBody Setmeal setmeal) throws Exception {
        setMealService.add(setmeal,checkgroupIds);
        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS,null);
    }

    @PostMapping("edit")
    public Result edit(@RequestBody Setmeal setmeal,
                       @RequestParam List<Integer>checkGroupIds){
        setMealService.edit(setmeal,checkGroupIds);
        return new Result(true, MessageConstant.EDIT_SETMEAL_SUCCESS,null);
    }

    @GetMapping("findById")
    public Result findById(@RequestParam Integer id){
        Setmeal setmeal=setMealService.findById(id);
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
    }

    @PostMapping("/findPage")
    public PageResult findById(@RequestBody QueryPageBean page){
        PageResult pageResult = setMealService.findPage(page);
        return  pageResult;
    }

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile imgFile) {
        try {
            String name = imgFile.getOriginalFilename();
            String extension = name.substring(name.lastIndexOf("."));
            String ObjectName = UUID.randomUUID().toString() + extension;
            String filePath = null;
            filePath = aliOssUtil.upload(imgFile.getBytes(), ObjectName);
            //将上传成功图片的路径和名字存在redis中
            redisTemplate.opsForValue().set("waitPass", filePath);
            return new Result(true, MessageConstant.UPLOAD_SUCCESS, filePath);
        } catch (IOException e) {
            return  new Result(false, MessageConstant.PIC_UPLOAD_FAIL,null);

        }

    }
}
